<script lang="ts" setup>
import {onBeforeMount, onMounted, ref} from 'vue'
import {ElMessage} from "element-plus";
import {getAPI} from "@/api/MyAxiosAPI";
import type {NoteInterface, ResponseInterface} from "@/type/models";
import Vditor from 'vditor'
import 'vditor/dist/index.css';
import NotePreview from "@/components/Note/NotePreview.vue";
// --- API ---
const MOCK = false
const API = getAPI(MOCK)
// --- end API ---

// --- 加载备忘录 ---
let noteList = ref<Array<NoteInterface>>([])

// 分页获取备忘录
function noteListAPI(page: number) {
    API({
        url: "/note/list/" + page,
        method: "get",
        headers: {
            Authorization: localStorage.getItem("token")
        }
    }).then((res) => {
        let r: ResponseInterface = res.data
        if (r.code == 200) {
            noteList.value = r.data
        }
    })
}

// 获取详细备忘录信息
function noteInfoAPI(noteId: string) {
    API({
        url: "/note/info",
        method: "get",
        headers: {
            Authorization: localStorage.getItem("token")
        },
        params: {
            "noteId": noteId
        }
    }).then((res) => {
        let r: ResponseInterface = res.data
        if (r.code == 200) {
            noteText.value = r.data.content
            noteTitle.value = r.data.title
            currentNoteId.value = r.data.noteId
            vditor.value.setValue(noteText.value)
            if (r.data.alarmTime === null) {
                alarmTime.value = ""
            } else {
                alarmTime.value = new Date(r.data.alarmTime)
            }
        }
    })
}

function clickUpdateNote(noteId: string) {
    goToWriteNotePage()
    noteInfoAPI(noteId)
}

// --- end 加载备忘录 ---

// --- 新建|编辑备忘录 ---
let noteText = ref('')
let noteTitle = ref<string>("")
let currentNoteId = ref("")
let alarmTime = ref<Date | string>("")
//vditor
const vditor = ref()
let loadingVditor = ref<boolean>(false)

function save() {
    if (currentNoteId.value.length == 0) {
        saveAPI()
    } else {
        updateAPI()
    }
}

function clearAlertTime() {
    alarmTime.value = ""
}

// 保存备忘录API
function saveAPI() {
    API({
        url: "/note/add",
        method: "post",
        headers: {
            Authorization: localStorage.getItem("token")
        },
        data: {
            "title": noteTitle.value,
            "content": noteText.value,
            "alarmTime": alarmTime.value
        }
    }).then((res) => {
        let r: ResponseInterface = res.data;
        if (r.code > 0) {
            ElMessage.success("保存成功")
            currentNoteId.value = r.data
        }
    })
}

// 更新备忘录API
function updateAPI() {
    API({
        url: "/note/update",
        method: "post",
        headers: {
            Authorization: localStorage.getItem("token")
        },
        data: {
            "noteId": currentNoteId.value,
            "content": noteText.value,
            "title": noteTitle.value,
            "alarmTime": alarmTime.value
        }
    }).then((res) => {
        let r: ResponseInterface = res.data;
        if (r.code > 0) {
            ElMessage.success("保存成功")
        }
    })
}

// --- end 新建|编辑备忘录 ---

// --- 备忘录页面跳转 ---
// 备忘录页面和新建备忘录页面切换
let showWriteNotePage = ref(false)

// 跳转到新建页面
function goToWriteNotePage() {
    showWriteNotePage.value = true
    noteTitle.value = ""
    noteText.value = ''
    vditor.value.setValue(noteText.value)
}

// 跳转到备忘录首页
function goBack() {
    showWriteNotePage.value = false
    currentNoteId.value = ""
    noteListAPI(1)
}

// --- end 备忘录页面跳转 ---

// --- 删除

/**
 * 删除具有特定noteId的笔记对象
 * @param noteId 要删除的笔记ID
 */
function deleteNoteArray(noteId: string) {
    noteList.value = noteList.value.filter((note: NoteInterface) => note.noteId != noteId)
}

/**
 * 删除笔记的API调用函数
 * @param {string} noteId - 要删除的笔记的ID
 */
function deleteNoteAPI(noteId: string) {
    API({
        url: "/note/realDelete",
        method: "delete",
        headers: {
            Authorization: localStorage.getItem("token")
        },
        data: {
            "noteId": noteId
        }
    }).then((res) => {
        let r: ResponseInterface = res.data;
        if (r.code == 200) {
            ElMessage.success("删除成功")
            deleteNoteArray(noteId)
        }
    })
}

// --- end 删除 ---

// 挂载
onBeforeMount(() => {
    noteListAPI(1)
})
onMounted(() => {
    vditor.value = new Vditor('vditor', {
        height: "420px",
        toolbar: [
            "undo", "redo",
            "|", "emoji", "headings", "bold", "italic", "strike", "link",
            "|", "list", "ordered-list", "check",
            "|", "code", "inline-code", "code-theme",
            "|", "line", "quote", "table", "edit-mode", "both", "preview", "fullscreen", "outline", "export", "info", "help", "br",
        ],
        toolbarConfig: {
            hide: false,
            pin: true
        },
        counter: {
            enable: true,
        },
        cache: {
            enable: false,
            id: currentNoteId.value,
        },
        preview: {
            markdown: {
                toc: false,
                sanitize: true,
            }
        },
        input(md) {
            noteText.value = md;
            loadingVditor.value = false
        },
        keydown(event) {
            loadingVditor.value = true
        },
    })
})
</script>

<template>
    <div class="common-layout">
        <div v-show="!showWriteNotePage">
            <el-button type="primary" @click="goToWriteNotePage">新建备忘录</el-button>
            <br/>
            <el-row>
                <el-col v-for="note in noteList" :key="note.noteId" :span="8">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="card-container">
                                <span class="card-name">
                                    {{ note.title }}
                                </span>
                                <el-button link @click="clickUpdateNote(note.noteId)" type="primary">编辑</el-button>
                                <el-popconfirm :hide-icon="true"
                                               cancel-button-text="取消"
                                               cancel-button-type="success"
                                               confirm-button-text="确认"
                                               confirm-button-type="danger"
                                               title="删除后不可恢复，是否删除？"
                                               @confirm="deleteNoteAPI(note.noteId)">
                                    <template #reference>
                                        <el-button link type="danger">删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </div>
                        </template>
                        <div>
                            <NotePreview :content="note.content" :note-id="note.noteId"></NotePreview>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <div v-show="showWriteNotePage">
            <el-page-header title="返回" @back="goBack">
                <template #content>
                    <el-date-picker
                        v-model="alarmTime"
                        placeholder="选择提醒时间"
                        type="datetime"
                    />
                    <el-button v-if="alarmTime instanceof Date" @click="clearAlertTime">清除提醒</el-button>
                    <el-button type="primary" @click="save" :loading="loadingVditor" :disabled="loadingVditor">保存</el-button>
                </template>
            </el-page-header>
            <el-input v-model="noteTitle" placeholder="请输入标题"/>
            <div id="vditor"></div>
        </div>
    </div>
</template>

<style scoped>
.bgc {
    background-color: #f0f2f5;
}

.card-container {
    display: flex;
    justify-content: flex-start; /* 默认值，可以省略 */
}

.card-name {
    margin-right: auto; /* 让文本与按钮之间有足够的间距 */
    line-height: 32px;
}

</style>